#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from flask import current_app, jsonify
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from app.libs.enums import ClientTypeEnum
from app.libs.redprint import RedPrint
from app.models.user import User
from app.vaildators.forms import ClientForm

view_api = RedPrint('token')


@view_api.route('/login', methods=['POST'])
def login():
    form = ClientForm().validate_for_api()

    promise = {
        ClientTypeEnum.USER_EMAIL: User.verify,
    }
    identity = promise[ClientTypeEnum(form.type.data)](
        form.account.data,
        form.secret.data
    )
    expiration = current_app.config['TOKEN_EXPIRATION']
    token = generate_auth_token(
        uid=identity['uid'],
        ac_type=form.type.data,
        scope=identity['scope'],
        expiration=expiration
    )
    response_token = {
        'token': token.decode('ascii')
    }

    return jsonify(response_token), 201


def generate_auth_token(uid, ac_type, scope=None, expiration=7200):
    serial = Serializer(
        current_app.config['SECRET_KEY'],
        expires_in=expiration
    )
    return serial.dumps(
        dict(
            uid=uid,
            type=ac_type.value,
            scope=scope
        )
    )
